package logic

import (
	"context"
	"fmt"
	"user/modles"
	"user/pkg"

	"user/user_rpc/internal/svc"
	"user/user_rpc/user_rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *user_rpc.UserLoginRequest) (*user_rpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line
	User := modles.User{
		UserAccount: in.UserAccount,
	}
	Password := pkg.Md5(in.UserPassword)
	Code := in.ImageCode
	get_code, _ := modles.Rdb.Get(modles.Ctx, fmt.Sprintf("ImageCaptcha_UserAccount:%s", in.UserAccount)).Result()
	if Code != get_code {
		return &user_rpc.UserLoginResponse{}, fmt.Errorf("验证码错误")
	}
	if modles.DB.Where("user_account = ?", User.UserAccount).Limit(1).Find(&User).Error != nil {
		return &user_rpc.UserLoginResponse{}, fmt.Errorf("服务器繁忙")
	}
	if User.ID == 0 {
		return &user_rpc.UserLoginResponse{}, fmt.Errorf("账号不存在")
	}
	if User.UserPassword != Password {
		return &user_rpc.UserLoginResponse{}, fmt.Errorf("密码或账号错误")
	}
	return &user_rpc.UserLoginResponse{
		UserId: int64(User.ID),
	}, nil
}
